package org.software.dao;
import org.software.entity.Student;

import java.util.*;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;


public class StudentDataProvider {
    private  static AtomicInteger studentIdGenerator = new AtomicInteger(0);
    private  static List<Student> students = new CopyOnWriteArrayList<>();

    public static boolean studentAdd(String studentId, String studentName, String groupName) {
        if(students.stream().anyMatch(s -> s.getStudentId().equals(studentId))){
            return false;
        }
        GroupDataProvider.incrementStudentCountForGroup(groupName);
        Student newStudent = new Student(studentIdGenerator.incrementAndGet(),studentId,studentName,groupName);
        students.add(newStudent);
        return true;
    }

    public static boolean studentDelete(String studentId) {
        for(Student student : students){
            if(student.getStudentId().equals(studentId)){
                GroupDataProvider.decrementStudentCountForGroup(student.getGroupName());
                students.remove(student);
                return true;
            }
        }
        return false;
    }
    public static Student getRandomStudent() {
        if(students.isEmpty()){
            return null;
        }
        int index = (int)(Math.random()*students.size());
        return students.get(index);
    }
    public static List<Student> studentQuery(){
        return new ArrayList<>(students);
    }
}
